package com.indobrains.uud1945.database;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {
	private static final String TAG = "UUD45";
	private static final String DB_NAME = "uud45.sqlite3";
	//private static final String DB_NEW = "uud45new.sqlite3";
	private static String DB_PATH = "/data/data/com.indobrains.uud1945/databases/";
	private static final int DATABASE_VERSION = 3;
	private SQLiteDatabase myDataBase;
	private Context myContext;
	private final String[] DATABASE_CREATE=
			{"CREATE TABLE _chapters (_id integer PRIMARY KEY AUTOINCREMENT,title text NOT NULL,description text,note varchar(20), older_version text);",
			"CREATE TABLE _amandemens (_id integer PRIMARY KEY AUTOINCREMENT,description text);",
			"CREATE TABLE _clauses (_id integer PRIMARY KEY AUTOINCREMENT,chapter_id integer NOT NULL,title text NOT NULL,amandemen integer NOT NULL);",
			"CREATE TABLE _paragraphs (_id integer PRIMARY KEY AUTOINCREMENT,clause_id integer NOT NULL,bullet varchar(10),content text,amandemen integer,older_version text);"};
	
	public DatabaseHelper(Context context) {
		super(context, DB_NAME, null, DATABASE_VERSION);
		// TODO Auto-generated constructor stub
		this.myContext = context;
		try {
			this.createDataBase();
		} catch (IOException ex){
			Log.e(TAG,ex.getMessage());
		}
	}
	public void createDataBase() throws IOException{
		 
		boolean dbExist = checkDataBase();
		 
		if(dbExist){
		//do nothing - database already exist
			compareDataBase();
			Log.d(TAG,"Database already exist");
		}else{
		 
		//By calling this method and empty database will be created into the default system path
		//of your application so we are gonna be able to overwrite that database with our database.
		this.getReadableDatabase();
		Log.d(TAG,"Database not exist");
		try {
		 
		copyDataBase();
		 
		} catch (IOException e) {
		 
		throw new Error("Error copying database");
		 
		}
		}
		 
	}
	private boolean checkDataBase(){
		 
		SQLiteDatabase checkDB = null;
		 
		try{
		String myPath = DB_PATH + DB_NAME;
		checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
		//Log.d(TAG, myPath); 
		}catch(SQLiteException e){
		 
		//Log.e(TAG,"Database Not Existen");
		 
		}
		 
		if(checkDB != null){
		 
		checkDB.close();
		 
		}
		 
		return checkDB != null ? true : false;
		}
		 
		/**
		  * Copies your database from your local assets-folder to the just created empty database in the
		  * system folder, from where it can be accessed and handled.
		  * This is done by transfering bytestream.
		  * */
	private void compareDataBase() throws IOException{
		InputStream input = myContext.getAssets().open("db/"+DB_NAME);
		long new_size=input.available(); 
		String oldFile = DB_PATH + DB_NAME;
		
		InputStream old_db=new FileInputStream(oldFile); 
		long old_size=old_db.available(); 
		if (old_size<new_size){
			copyDataBase();
		}
		input.close();
		old_db.close();
		
	}
		private void copyDataBase() throws IOException{
		 
		//Open your local db as the input stream
		InputStream myInput = myContext.getAssets().open("db/"+DB_NAME);
		 
		// Path to the just created empty db
		String outFileName = DB_PATH + DB_NAME;
		 
		//Open the empty db as the output stream
		OutputStream myOutput = new FileOutputStream(outFileName);
		 
		//transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer))>0){
		myOutput.write(buffer, 0, length);
		}
		 
		//Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();
		Log.d(TAG,"Copy database success!"); 
		}
		 
		public void openDataBase() throws SQLException{
		 
		//Open the database
		String myPath = DB_PATH + DB_NAME;
		myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
		 
		}
		 
		@Override
		public synchronized void close() {
		 
		if(myDataBase != null)
		myDataBase.close();
		 
		super.close();
		 
		}
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
//		for (int i=0;i<DATABASE_CREATE.length;i++){
//			db.execSQL(DATABASE_CREATE[i]);
//		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub

	}

}
